package recolhalixo;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import jadex.bdi.runtime.IMessageEvent;
import jadex.bdi.runtime.Plan;
import jadex.bdi.runtime.Plan.SyncResultListener;
import jadex.bridge.IComponentIdentifier;
import jadex.bridge.fipa.SFipa;
import jadex.bridge.service.types.cms.CMSComponentDescription;
import jadex.extension.envsupport.environment.ISpaceAction;
import jadex.extension.envsupport.environment.ISpaceObject;
import jadex.extension.envsupport.environment.space2d.Grid2D;
import jadex.extension.envsupport.environment.space2d.Space2D;
import jadex.extension.envsupport.math.IVector2;
import jadex.extension.envsupport.math.Vector1Int;

public class PlanoPassear extends Plan {

	@Override
	public void body() {
		Grid2D env = (Grid2D)getBeliefbase().getBelief("env").getFact();
		Map params = new HashMap();
		String direction = null;
		Object oid = env.getAvatar(getComponentDescription()).getId();
		ISpaceObject obj = env.getSpaceObject(oid);
		IVector2 pos = (IVector2)obj.getProperty(Space2D.PROPERTY_POSITION);
		BaseConhecimento bc = (BaseConhecimento)getBeliefbase().getBelief("knows").getFact();
		bc.setTick((long)getClock().getTick());
		getBeliefbase().getBelief("knows").setFact(bc);
		
		// MENSAGENS
		Broadcaster.broadcastGarbage(this);
		
		// ANDAR
		Collection estrada = ((Grid2D) env).getSpaceObjectsByGridPosition(pos, "estrada");
		
		if(estrada == null){
			direction = "udlr";
			
		}else{
			direction = (String)((ISpaceObject)estrada.iterator().next()).getProperty("direction");
		}
		
		int index = new Random().nextInt(direction.length());
		params.put(AccaoMover.DIRECCAO, direction.charAt(index)+"");
		params.put("quantity", getBeliefbase().getBelief("quantity").getFact());
		
		params.put(ISpaceAction.OBJECT_ID, env.getAvatar(getComponentDescription()).getId());
		
		SyncResultListener srl	= new SyncResultListener();
		env.performSpaceAction("mover", params, srl); 
		srl.waitForResult();
	}
	
}
